﻿using System;
using System.Collections.Generic;
using wojilu.Apps.Qycms.Domain;
using wojilu.Apps.Qycms.Helper;
using wojilu.Members.Interface;
using wojilu.Members.Sites.Domain;
using wojilu.Members.Sites.Service;
using wojilu.Members.Users.Domain;
using wojilu.Web.Controller.Common;
using wojilu.Web.Mvc.Attr;

namespace wojilu.Web.Controller.Admin.Qycms
{
    public class FormController : BaseController
    {
        public virtual IAdminLogService<SiteLog> logService { get; set; }

        public FormController()
        {
            logService = new SiteLogService();
        }

        private void setpublic()
        {
            User user = ctx.viewer.obj as User;
            var modelPowerGroup = PowerGroup.findById(user.GroupId);
            bind("powergroup", modelPowerGroup);
        }

        [HttpGet, HttpPost]
        public virtual void FormList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            var condition = " lng='" + DefaultLng + "'";
            DataPage<Form_Group> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " and isclass = 1 ";
                    break;

                case 2:
                    condition += " and isclass = 0 ";
                    break;
            }
            var isseccode = ctx.GetInt("isseccode");
            switch (isclass)
            {
                case 1:
                    condition += " and isseccode = 1 ";
                    break;

                case 2:
                    condition += " and isseccode = 0 ";
                    break;
            }

            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Form_Group.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void FormAdd()
        {
            SetPublic();
            setpublic();
            target(FormAddDo);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", 1);
            set("tab", ctx.Get("tab"));
            var lng = DefaultLng;
            set("lng", lng);
            var memberpuvlist = Member_Class.findAll();
            bind("memberpuvlist", memberpuvlist);
            var tl = cdb.findAll<TimeList>();
            bind("timelist", tl);
        }

        [HttpPost]
        public virtual void FormAddDo()
        {
            var fg = new Form_Group();
            fg.pid = 50;
            fg.lng = ctx.Post("lng");
            fg.formgroupname = ctx.Post("formgroupname");
            fg.formcode = ctx.Post("formcode");
            fg.template = ctx.Post("template");
            fg.content = ctx.PostHtmlAll("content");
            fg.successtext = ctx.PostHtmlAll("successtext");
            fg.ismenu = ctx.PostInt("ismenu");
            fg.purview = ctx.PostInt("purview");
            fg.ismail = ctx.PostInt("ismail");
            fg.putmail = ctx.Post("putmail");
            fg.emailatt = ctx.Post("emailatt");
            fg.mailcode = ctx.Post("mailcode");
            fg.isseccode = ctx.PostInt("isseccode");
            fg.inputtime = ctx.PostInt("inputtime");
            fg.issms = ctx.PostInt("issms");
            fg.smscode = ctx.Post("smscode");
            fg.addtime = DateTime.Now;
            fg.isclass = 1;
            Result result = fg.insert();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_add_log") + lang("log_extra_ok"), "{Id:" + fg.Id + ", Name:'" + fg.formgroupname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void FormEdit(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(FormEditDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("type", ctx.Get("type"));
            Form_Group a = Form_Group.findById(Id);
            bind("formread", a);
            var memberpuvlist = Member_Class.findAll();
            bind("memberpuvlist", memberpuvlist);
            var tl = cdb.findAll<TimeList>();
            bind("timelist", tl);
        }

        [HttpPost]
        public virtual void FormEditDo(Int64 Id)
        {
            var fg = Form_Group.findById(Id);
            fg.formgroupname = ctx.Post("formgroupname");
            fg.template = ctx.Post("template");
            fg.content = ctx.PostHtmlAll("content");
            fg.successtext = ctx.PostHtmlAll("successtext");
            fg.ismenu = ctx.PostInt("ismenu");
            fg.purview = ctx.PostInt("purview");
            fg.ismail = ctx.PostInt("ismail");
            fg.putmail = ctx.Post("putmail");
            fg.emailatt = ctx.Post("emailatt");
            fg.mailcode = ctx.Post("mailcode");
            fg.isseccode = ctx.PostInt("isseccode");
            fg.inputtime = ctx.PostInt("inputtime");
            Result result = fg.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_edit_log") + lang("log_extra_ok"), "{Id:" + fg.Id + ", Name:'" + fg.formgroupname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void FormDel(Int64 Id)
        {
            Form_Group bt = Form_Group.findById(Id);
            if (bt.delete() > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_del_log") + lang("log_extra_ok"), "{Id:" + bt.Id + ", Name:'" + bt.formgroupname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_del_log") + lang("log_extra_no"), "{Erros:''}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
        }

        [HttpGet, HttpPost]
        public virtual void CheckFormName()
        {
            var lng = ctx.Get("lng");
            var formcode = ctx.Post("formcode");
            if (Form_Group.find(" formcode=:f and lng=:l").set("f", formcode).set("l", lng).first() == null)
            {
                ctx.web.ResponseWrite("true");
            }
            else
            {
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void FormSetting()
        {
            string Ids = ctx.PostIdList("selectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<Form_Group>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_isclass_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_isclass_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void MessList()
        {
            SetPublic();
            setpublic();
            set("load", to(new AdminController().Load) + "?");
            set("view", to(new QycmsController().Admin_Tab_List));
            var fgid = ctx.GetInt("fgid");
            var condition = " fgid =" + fgid;
            DataPage<Form_Value> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            var isreply = ctx.GetInt("isreply");
            switch (isreply)
            {
                case 1:
                    condition += " and isreply = 1 ";
                    break;

                case 2:
                    condition += " and isreply = 0 ";
                    break;
            }
            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Form_Value.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpPost]
        public virtual void FormMessageDel()
        {
            string Ids = ctx.PostIdList("messselectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Form_Value>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("forummain_del_log") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("forummain_del_log") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void FormMessageSetting()
        {
            string Ids = ctx.PostIdList("messselectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<Form_Value>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("forumtype_log_istype") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("forumtype_log_istype") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void FormMessMainRead(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(FormMessMainReadDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            var read = db.RunReader<Form_Value>("select * from ybb_form_value where Id=" + Id);
            bind("read", read);
            var form = Form_Group.findById(read["fgid"].ObjectToInt());
            bind("form", form);
            var docread = Document.findById(read["did"].ObjectToInt());
            bind("docread", docread);
            var attrlist = Form_Attr.find(" fgid =:f").set("f", form.Id).list();
            bind("attrlist", attrlist);
        }

        [HttpPost]
        public virtual void FormMessMainReadDo(Int64 Id)
        {
            var fv = Form_Value.findById(Id);
            fv.retime = DateTime.Now;
            //fv.isreply = 1;
            fv.isreply = 0;
            fv.recontent = ctx.PostHtmlAll("content");
            Result result = fv.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmessmain_edit_log") + lang("log_extra_no"), "{Id:" + Id + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                if (ctx.PostInt("ismail") == 1)
                {
                    var email = ctx.Post("email");
                    if (!email.StrIsNullOrEmpty())
                    {
                        var mailcode = "formreremind";
                        var bllMailSend = new YBBMailSend();
                        var dic = new Dictionary<string, object>();
                        dic["Id"] = Id;
                        bllMailSend.MailSend(mailcode, email, DefaultLng, dic);
                    }
                }
                logService.Add((User)ctx.viewer.obj, lang("formmessmain_edit_log") + lang("log_extra_ok"), "{Id:" + Id + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void ForMattList()
        {
            SetPublic();
            setpublic();
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");

            var fgid = ctx.GetInt("fgid");
            var condition = String.Empty;
            DataPage<Form_Attr> list = null;
            Int32 maxperpage = ctx.PostInt("MaxPerPage");
            Int32 page_id = ctx.PostInt("page_id") + 1;
            String limitkey = ctx.Get("limitkey");
            String limitclass = ctx.Get("limitclass");
            condition += " fgid=" + fgid;
            var isclass = ctx.GetInt("isclass");
            switch (isclass)
            {
                case 1:
                    condition += " and isclass = 1 ";
                    break;

                case 2:
                    condition += " and isclass = 0 ";
                    break;
            }
            var isvalidate = ctx.GetInt("isvalidate");
            switch (isvalidate)
            {
                case 1:
                    condition += " and isvalidate = 1 ";
                    break;

                case 2:
                    condition += " and isvalidate = 0 ";
                    break;
            }
            var isline = ctx.GetInt("isline");
            switch (isvalidate)
            {
                case 1:
                    condition += " and isline = 1 ";
                    break;

                case 2:
                    condition += " and isline = 0 ";
                    break;
            }

            if (strUtil.IsNullOrEmpty(limitkey)) limitkey = "id";
            if (strUtil.IsNullOrEmpty(limitclass)) limitclass = "desc";
            condition += " order by " + limitkey + " " + limitclass;
            CurrentRequest.setCurrentPage(page_id);
            list = Form_Attr.findPage(condition, maxperpage);
            if (ctx.web.postValueAll().Count == 0)
            {
                ctx.web.ResponseWrite(list.RecordCount.ToString());
                ctx.web.ResponseEnd();
            }
            bind("list", list.Results);
        }

        [HttpGet]
        public virtual void FormAttrAdd(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(FormAttrAddDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", 1);
            set("tab", "true");
            var lng = DefaultLng;
            set("lng", lng);
            set("fgid", Id);
            var list = cdb.findAll<FormType>();
            bind("list", list);
        }

        [HttpPost]
        public virtual void FormAttrAddDo(Int64 Id)
        {
            var attrname = ctx.Post("attrname").ToLower();
            var inputtype = ctx.Post("inputtype");
            var attrlenther = 0;
            Form_Attr a = Form_Attr.find(" attrname =:a and Id =:i").set("a", attrname).set("i", Id).first();
            if (a == null)
            {
                var list = Form_Attr.find(" attrname =:a").set("a", attrname).list();
                if (list.Count == 0)
                {
                    var list1 = cdb.findAll<FormType>();
                    foreach (var row in list1)
                    {
                        if (row.Key == inputtype)
                        {
                            attrlenther = row.VarLong;
                            switch (row.Key)
                            {
                                case "string":
                                case "img":
                                case "addon":
                                case "video":
                                case "select":
                                case "radio":
                                case "checkbox":
                                case "selectinput":
                                    var sql = "ALTER TABLE `ybb_form_value` ADD `" + attrname + "` " + row.Alter + "( " + row.VarLong + " );";
                                    db.RunSql(sql);
                                    break;

                                case "text":
                                case "editor":
                                case "htmltext":
                                    sql = "ALTER TABLE `ybb_form_value` ADD `" + attrname + "` " + row.Alter + ";";
                                    db.RunSql(sql);
                                    break;

                                case "int":
                                    sql = "ALTER TABLE `ybb_form_value` ADD `" + attrname + "` " + row.Alter + " DEFAULT 0;";
                                    db.RunSql(sql);
                                    break;

                                case "float":
                                case "decimal":
                                    sql = "ALTER TABLE `ybb_form_value` ADD `" + attrname + "` " + row.Alter + ";";
                                    db.RunSql(sql);
                                    break;

                                case "datetime":
                                    sql = "ALTER TABLE `ybb_form_value` ADD `" + attrname + "` " + row.Alter + ";";
                                    db.RunSql(sql);
                                    break;
                            }
                        }
                    }
                }
                var fa = new Form_Attr();
                fa.pid = 50;
                fa.fgid = Id;
                fa.typename = ctx.Post("typename");
                fa.typeremark = ctx.Post("typeremark");
                fa.attrname = attrname;
                fa.inputtype = inputtype;
                fa.attrvalue = ctx.Post("attrvalue");
                fa.attrsize = ctx.PostInt("attrsize");
                fa.attrrow = ctx.PostInt("attrrow");
                fa.attrlenther = attrlenther;
                fa.isvalidate = ctx.PostInt("isvalidate");
                fa.validatetext = ctx.Post("validatetext");
                fa.isclass = ctx.PostInt("isclass");
                fa.isline = 0;
                Result result = fa.insert();
                if (result.HasErrors)
                {
                    logService.Add((User)ctx.viewer.obj, lang("formmain_attr_add_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                    ctx.web.ResponseWrite("false");
                }
                else
                {
                    logService.Add((User)ctx.viewer.obj, lang("formmain_attr_add_log") + lang("log_extra_ok"), "{Id:" + fa.Id + ", Name:'" + fa.attrname + "'}", "", ctx.Ip);
                    ctx.web.ResponseWrite("true");
                }
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_add_log") + lang("log_extra_no"), "{attrname:'" + attrname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet]
        public virtual void FormAttrEdit(Int64 Id)
        {
            SetPublic();
            setpublic();
            target(FormAttrAddDo, Id);
            set("iframename", ctx.Get("iframename"));
            set("iframeheightwindow", ctx.GetInt("iframeheightwindow"));
            set("load", to(new AdminController().Load) + "?");
            set("refalse", 1);
            var fa = Form_Attr.findById(Id);
            bind("attrread", fa);
            var list = cdb.findAll<FormType>();
            bind("list", list);
        }

        [HttpPost]
        public virtual void FormAttrEditDo(Int64 Id)
        {
            var formattr = Form_Attr.findById(Id);
            formattr.typename = ctx.Post("typename");
            formattr.typeremark = ctx.Post("typeremark");
            formattr.attrvalue = ctx.Post("attrvalue");
            formattr.isvalidate = ctx.PostInt("isvalidate");
            formattr.validatetext = ctx.Post("validatetext");
            formattr.attrsize = ctx.PostInt("attrsize");
            formattr.attrrow = ctx.PostInt("attrrow");
            formattr.isclass = ctx.PostInt("isclass");
            Result result = formattr.update();
            if (result.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_edit_log") + lang("log_extra_no"), "{Erros:'" + result.ErrorsText + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_edit_log") + lang("log_extra_ok"), "{Id:" + formattr.Id + ", Name:'" + formattr.attrname + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            ctx.web.ResponseEnd();
        }

        [HttpGet, HttpPost]
        public virtual void CheckAttrName()
        {
            var attrname = ctx.Post("attrname").ToLower();
            var inputtype = ctx.Get("inputtype");
            var fgid = ctx.GetInt("fgid");
            Form_Attr fa = Form_Attr.find(" attrname =:a and Id =:i").set("a", attrname).set("i", fgid).first();
            if (fa != null)
            {
                ctx.web.ResponseWrite("false");
                ctx.web.ResponseEnd();
            }
            else
            {
                var list = Form_Attr.find(" attrname =:a").set("a", attrname).list();
                if (list.Count > 0)
                {
                    foreach (var row in list)
                    {
                        if (row.inputtype == inputtype)
                        {
                            ctx.web.ResponseWrite("true");
                            break;
                        }
                    }
                    ctx.web.ResponseWrite("false");
                }
                else
                {
                    ctx.web.ResponseWrite("true");
                }
                ctx.web.ResponseEnd();         
            }
        }

        [HttpPost]
        public virtual void DelFormAttr()
        {
            string Ids = ctx.PostIdList("attrselectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            if (db.deleteBatch<Form_Attr>(condition) > 0)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_log_del") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_log_del") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void AttrSort()
        {
            var infoid = ctx.PostIdList("infoid");
            var pid = ctx.PostIdList("pid");
            var strArray = infoid.Split(new char[] { ',' });
            var strArray1 = pid.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                string condition = string.Format("Id = {0}", strArray[i]);
                db.updateBatch<Form_Attr>("set pid=" + strArray1[i], condition);
            }
            logService.Add((User)ctx.viewer.obj, lang("formmain_attr_log_sort") + lang("log_extra_ok"), "{Id:" + infoid + "'}", "", ctx.Ip);
            ctx.web.ResponseWrite("true");
            ctx.web.ResponseEnd();
        }

        [HttpPost]
        public virtual void AttrSetting()
        {
            string Ids = ctx.PostIdList("attrselectinfoid");
            string condition = string.Format("Id in ({0})", Ids);
            var value = ctx.Post("value");
            var dbname = ctx.Post("dbname");
            db.updateBatch<Form_Attr>("set " + dbname + "=" + value, condition);
            if (!ctx.HasErrors)
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_log_istype") + lang("log_extra_ok"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("true");
            }
            else
            {
                logService.Add((User)ctx.viewer.obj, lang("formmain_attr_log_istype") + lang("log_extra_no"), "{Id:" + Ids + "'}", "", ctx.Ip);
                ctx.web.ResponseWrite("false");
            }
            ctx.web.ResponseEnd();
        }

    }
}
